package br.com.gbvbahia.vendas.controllers;

import br.com.gbvbahia.vendas.modelos.Endereco;

import java.io.Serializable;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@Named("enderecoController")
@SessionScoped
public class EnderecoController implements Serializable {

    @EJB
    private br.com.gbvbahia.vendas.beans.EnderecoFacade ejbFacade;

    public Endereco getEndereco(java.lang.Long id) {
        return ejbFacade.find(id);
    }

    @FacesConverter(forClass = Endereco.class)
    public static class EnderecoControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            EnderecoController controller = (EnderecoController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "enderecoController");
            return controller.getEndereco(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Endereco) {
                Endereco o = (Endereco) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Endereco.class.getName());
            }
        }
    }
}
